package com.mmp.main.servlet.joborder;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.bo.Message;
import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.DB.DBQueryManager;
import com.mmp.main.endpoints.JobOrderNotificationsEndPoint;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.entity.JobOrder;
import com.mmp.main.util.Default;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

public class JobOrderOpenProcessServlet extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String deviceId = request.getParameter("deviceId");

		if (deviceId == null || deviceId.isEmpty()) {
			announceErorrMessage(request, response, Default.GENERAL_ERROR_MESSAGE);
			return;
		}

		HospitalDevice device = dbm.findById(Integer.parseInt(deviceId), HospitalDevice.class);
		device.setStatus(Enums.DEVICE_STATUS.UNDER_MAINTENANCE.getStatus());
		device = dbm.mergeEntity(device);

		JobOrder order = new JobOrder();
		order.setHospitalDevice(device);
		order.setJobOrderNo(WebUtil.getParamValue(request, "jobOrderNo", null));
		order.setJobOrderDate(WebUtil.getParamValueAsDate(request, "jobOrderDate", null));
		order.setDamageDescription(WebUtil.getParamValue(request, "damageDescription", null));
		order.setDamageDate(WebUtil.getParamValueAsDate(request, "damageDate", null));
		order.setCancelled(false);
		order.setClosed(false);
		order.setOpenedBy(getSessionUser(request));
		order.setOpenedIn(new Date());

		// dbm.persistEntity(order);
		dbm.mergeEntity(order);

		setMessage(request, new Message("تم فتح امر عمل للجهاز", Message.MESSAGE_TYPE.SUCCESS));
		
		JobOrderNotificationsEndPoint.sendMessageToAll(new DBQueryManager(dbm).getNotification());

		sendRedirect(
				request,
				response,
				"SearchForDeviceToOpenJobOrder?" + Default.SEARCH_DEST_PARAM_NAME + "="
						+ Default.SEARCH_DEST_OPEN_JOB_OREDR_PARAM_VALUE);
	}
}
